package com.zd.kids.ui.fragment;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.blankj.utilcode.util.FileUtils;
import com.hyy.libray.presenter.IBasePresenter;
import com.hyy.libray.ui.fragment.BaseFragment;
import com.zd.kids.DataBean.BaseDataBean;
import com.zd.kids.DataBean.TrainWordDataBean;
import com.zd.kids.R;
import com.zd.kids.common.Constants;
import com.zd.kids.common.GlideUtil;
import com.zd.kids.common.MAudioPlayer;
import com.zd.kids.common.ToastUtils;
import com.zd.kids.net.CustomObserver;
import com.zd.kids.net.HttpMethod;
import com.zd.kids.ui.adapter.WordTitleAdapter;
import com.zd.kids.ui.view.WaveView;
import com.zlw.main.recorderlib.RecordManager;
import com.zlw.main.recorderlib.recorder.RecordHelper;
import com.zlw.main.recorderlib.recorder.listener.RecordDataListener;
import com.zlw.main.recorderlib.recorder.listener.RecordResultListener;

import java.io.File;
import java.util.concurrent.TimeUnit;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class TrainWordFragment extends BaseFragment {
    private static final String ARG_PARAM1 = "param1";
    @BindView(R.id.img_bg)
    ImageView imgBg;
    @BindView(R.id.img_origin_audio)
    ImageView imgOriginAudio;
    @BindView(R.id.img_record)
    ImageView imgRecord;
    @BindView(R.id.img_record_audio)
    ImageView imgRecordAudio;

    @BindView(R.id.wave_view)
    WaveView waveView;

    @BindView(R.id.recycle_view)
    RecyclerView recycleView;

    @BindView(R.id.rl_end)
    LinearLayout rlEnd;

    private RecordManager recordManager;

    private String mOrginAudio = "";


    private MAudioPlayer mOriginAudioPlayer;

    private MAudioPlayer mRecordAudioPlayer;

    private String mRecordFileName;

    private boolean isRecording;

    private boolean isPlayRecordAudio;
    private boolean isPlayOriginAudio;

    public TrainWordFragment() {

    }

    public static TrainWordFragment newInstance(TrainWordDataBean.ResultBean resultBean) {
        TrainWordFragment fragment = new TrainWordFragment();
        Bundle args = new Bundle();
        args.putSerializable("TrainWordDataBean", resultBean);
        fragment.setArguments(args);
        return fragment;
    }

    private TrainWordDataBean.ResultBean resultDataBean;


    private boolean isEndWord;

    private String unitId;

    public void setEndWord(boolean endWord) {
        isEndWord = endWord;
    }

    public void setUnitId(String unitId) {
        this.unitId = unitId;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            resultDataBean = (TrainWordDataBean.ResultBean) getArguments().getSerializable("TrainWordDataBean");

            mOrginAudio = resultDataBean.getAudio_path();
            mRecordFileName = resultDataBean.getTitle() + "_" + resultDataBean.getNewwordid() + "_0";
        }
    }

    /**
     * 获取布局文件地址
     */
    @Override
    public int getLayoutResId() {
        return R.layout.fragment_train_word;
    }

    private WordTitleAdapter wordTitleAdapter;

    /**
     * 初始化布局
     *
     * @param view
     */
    @Override
    public void initView(View view) {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        recycleView.setLayoutManager(linearLayoutManager);
        wordTitleAdapter = new WordTitleAdapter(resultDataBean.getWordTitles());
        recycleView.setAdapter(wordTitleAdapter);

        GlideUtil.load(resultDataBean.getImg_path(), imgBg, R.mipmap.ic_train_word_bg);
        waveView.setVisibility(View.GONE);
    }

    @Override
    public void onResume() {
        super.onResume();
        initRecordEvent();
    }

    private boolean isPreparRecord;

    private void setRecordStatus(int status) {
        isPreparRecord = true;
        if (status == 0) {
            isPreparRecord = false;
            imgRecord.setImageResource(R.mipmap.ic_recoder_default_gray);
        } else if (status == 1) {
            imgRecord.setImageResource(R.mipmap.ic_record_default);
        }

    }

    private void setAudioPlayerStatus(int status) {
        if (status == 0 || status == 1) {
            imgOriginAudio.setImageResource(R.mipmap.ic_play_origin_default);
        } else if (status == 2) {
            imgOriginAudio.setImageResource(R.mipmap.ic_play_origin_playing);
        }
    }

    private void setRecordPlayerStatus(int status) {
        if (status == 0) {
            imgRecordAudio.setImageResource(R.mipmap.ic_play_record_default);
        } else if (status == 1) {
            imgRecordAudio.setImageResource(R.mipmap.ic_play_recording);
        } else if (status == 2) {
            imgRecordAudio.setImageResource(R.mipmap.ic_play_record_playing);
        }
    }


    /**
     * 初始化数据
     */
    @Override
    public void initData() {
        mOriginAudioPlayer = new MAudioPlayer();
        mOriginAudioPlayer.setAudioPlayerStatus(new MAudioPlayer.AudioPlayerStatus() {
            @Override
            public void playerPause() {

                if (imgOriginAudio != null) {
                    imgOriginAudio.setImageResource(R.mipmap.ic_play_origin_default);
                    setRecordStatus(1);
                    setAudioPlayerStatus(1);
                    setAudioPlayerStatus(1);
                }

            }

            @Override
            public void playerCompletion(MediaPlayer mp) {
                isPlayOriginAudio = false;
                Log.i("playRecorAudio", isPlayRecordAudio + "imgOriginAudio,playerCompletion");
                if (isPlayRecordAudio) {
                    Log.i("playRecorAudio", "playRecorAudio" + isPlayRecordAudio);
                    mRecordAudioPlayer.playUrl(Constants.RECORD_ROOT_PATH + mRecordFileName + ".wav");
                } else {
                    if (imgOriginAudio != null) {
                        imgOriginAudio.setImageResource(R.mipmap.ic_play_origin_default);
                        setRecordStatus(1);
                        setAudioPlayerStatus(1);
                    }
                }
            }

            @Override
            public void playerPrepared(MediaPlayer mp) {
                mp.start();

                if (isPlayRecordAudio) {
                    setRecordPlayerStatus(2);
                } else {
                    setAudioPlayerStatus(2);
                }

            }

            @Override
            public void playerStart() {
            }

            @Override
            public void playerError(MediaPlayer mp, int what, int extra) {
                isPlayOriginAudio = false;
            }
        });

        mRecordAudioPlayer = new MAudioPlayer();
        mRecordAudioPlayer.setAudioPlayerStatus(new MAudioPlayer.AudioPlayerStatus() {
            @Override
            public void playerPause() {
                setRecordPlayerStatus(1);
            }

            @Override
            public void playerCompletion(MediaPlayer mp) {
                Log.i("playRecorAudio", isPlayRecordAudio + "mRecordAudioPlayer,playerCompletion");
                isPlayRecordAudio = false;
                showComplteView();
                setRecordPlayerStatus(1);
            }

            @Override
            public void playerPrepared(MediaPlayer mp) {
                mp.start();
                setRecordPlayerStatus(2);
            }

            @Override
            public void playerStart() {

            }

            @Override
            public void playerError(MediaPlayer mp, int what, int extra) {

            }
        });
    }

    private void showComplteView() {
        if (isEndWord) {
            rlEnd.setVisibility(View.VISIBLE);
            completeTrainWord();
        }
    }

    /**
     * 获取Presenter，不用MVP，可以为空
     *
     * @return
     */
    @Override
    protected IBasePresenter onBasePresenter() {
        return null;
    }


    @OnClick({R.id.img_origin_audio, R.id.img_leave, R.id.img_restart, R.id.img_record, R.id.img_record_audio})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_origin_audio:
                if (isRecording || isPlayRecordAudio || isPlayOriginAudio) {
                    return;
                }

                if (!TextUtils.isEmpty(mOrginAudio)) {
                    isPlayOriginAudio = true;
                    mOriginAudioPlayer.playUrl(mOrginAudio);
                } else {
                    ToastUtils.getIntence().makeTextShow(getString(R.string.data_error_tips));
                }

                break;
            case R.id.img_record:

                if (isPlayRecordAudio || isPlayOriginAudio || !isPreparRecord) {
                    return;
                }

                recordAudioProcessor();
                break;
            case R.id.img_record_audio:

                if (isRecording || isPlayRecordAudio || isPlayOriginAudio || isPlayRecordAudio || !isHaveRecodeFile(mRecordFileName)) {
                    return;
                }

                playRecorAudio();
                break;
            case R.id.img_leave:
                rlEnd.setVisibility(View.GONE);
                getActivity().finish();
                break;
            case R.id.img_restart:
                rlEnd.setVisibility(View.GONE);
                break;
        }
    }


    /**
     * 录音处理
     */
    private void recordAudioProcessor() {
        if (isRecording) {
            stopRecodAudio();
        } else {
            startRecordAudio();
        }

    }


    private void initRecordEvent() {
        recordManager = RecordManager.getInstance();
        recordManager.setRecordDataListener(new RecordDataListener() {
            @Override
            public void onData(byte[] data) {
                if (waveView != null) {
                    waveView.addData(data);
                }

            }
        });

        recordManager.setRecordResultListener(new RecordResultListener() {
            @Override
            public void onResult(File result) {
                if (waveView != null) {
                    setRecordPlayerStatus(1);
                    imgRecord.setImageResource(R.mipmap.ic_record_default);
                    waveView.setVisibility(View.GONE);
                }
            }
        });

    }


    private void startRecordAudio() {

        if (recordManager.getState() != RecordHelper.RecordState.STOP) {
            stopRecodAudio();
        }
        FileUtils.delete(Constants.RECORD_ROOT_PATH + mRecordFileName + ".wav");

        isRecording = true;
        imgRecord.setImageResource(R.mipmap.ic_recording);
        recordManager.start(mRecordFileName);
        waveView.setVisibility(View.VISIBLE);
        startInverTime();
    }


    private void stopRecodAudio() {
        if (isRecording) {
            isRecording = false;
        }
        if (recordManager != null) {
            recordManager.stop();
        }

        if (disposable != null) {
            disposable.dispose();
        }
    }


    private int mRecodAudioTime = 4 * 1000 + 300;

    private Disposable disposable;

    private void startInverTime() {
        Observable.timer(mRecodAudioTime, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        stopRecodAudio();
                    }
                });
    }


    @Override
    public void onPause() {
        super.onPause();

        if (mOriginAudioPlayer != null) {
            mOriginAudioPlayer.pause();
        }
        stopRecodAudio();

        if (mRecordAudioPlayer != null) {
            mRecordAudioPlayer.pause();
        }

        FileUtils.delete(Constants.RECORD_ROOT_PATH + mRecordFileName + ".wav");

        resertView();
    }

    @Override
    public void onDestroy() {
        stopRecodAudio();
        if (mOriginAudioPlayer != null) {
            mOriginAudioPlayer.stop();
        }

        if (mRecordAudioPlayer != null) {
            mRecordAudioPlayer.stop();
        }
        super.onDestroy();
    }


    private void playRecorAudio() {

        Log.i("playRecorAudio", "playRecorAudio" + isPlayRecordAudio);
        isPlayRecordAudio = true;

        mOriginAudioPlayer.playUrl(mOrginAudio);
    }


    private boolean isHaveRecodeFile(String fileNam) {
        return FileUtils.isFile(Constants.RECORD_ROOT_PATH + fileNam + ".wav");
    }


    private boolean isComplte;

    private void completeTrainWord() {

        if (isEndWord && !TextUtils.isEmpty(unitId) && !isComplte) {
            HttpMethod.getIntence().setTrainCompleteResult(unitId, new CustomObserver<BaseDataBean>(getContext()) {
                @Override
                public void onSuccess(BaseDataBean baseDataBean) {
                    isComplte = true;
                }

                @Override
                public void onError(String errorCode) {

                }
            });
        }

    }

    private void resertView() {

        mRecordAudioPlayer.pause();
        mOriginAudioPlayer.pause();
        recordManager.stop();

        setRecordStatus(0);
        setRecordPlayerStatus(0);

        isPlayRecordAudio = false;
        isPreparRecord = false;
        isRecording = false;
    }


}
